from minio import Minio
from config import MINIO_CONFIG
import io
import mimetypes
from minio.error import S3Error

class MinioService:
    def __init__(self):
        self.client = Minio(
            MINIO_CONFIG['endpoint'],
            access_key=MINIO_CONFIG['access_key'],
            secret_key=MINIO_CONFIG['secret_key'],
            secure=MINIO_CONFIG['secure']
        )
        self.bucket_name = MINIO_CONFIG['bucket_name']
        self._ensure_bucket()
    
    def _ensure_bucket(self):
        if not self.client.bucket_exists(MINIO_CONFIG['bucket_name']):
            self.client.make_bucket(MINIO_CONFIG['bucket_name'])
    
    def upload_file(self, object_name: str, data, size: int):
        return self.client.put_object(
            MINIO_CONFIG['bucket_name'],
            object_name,
            data,
            size
        )
    
    def delete_file(self, object_name: str):
        """删除MinIO中的文件"""
        try:
            self.client.remove_object(
                bucket_name=MINIO_CONFIG['bucket_name'],
                object_name=object_name
            )
        except Exception as e:
            raise Exception(f"Failed to delete file from MinIO: {str(e)}")
        
    def download_file(self, file_path):
        """
        从 Minio 下载文件：
        参数 file_path：在Minio中的对象名称
        返回 (file_obj, filename, mimetype) 或 None
        """
        try:
            response = self.client.get_object(self.bucket_name, file_path)
            file_data = response.read()  # 读取整个文件内容
            response.close()             # 关闭响应
            response.release_conn()      # 释放连接

            file_obj = io.BytesIO(file_data)
            filename = file_path.split("/")[-1]
            mimetype, _ = mimetypes.guess_type(filename)
            if not mimetype:
                mimetype = "application/octet-stream"
            return file_obj, filename, mimetype
        except S3Error as s3e:
            print("Minio下载文件 S3Error:", s3e)
            return None
        except Exception as e:
            print("MinioService.download_file 异常:", e)
            return None